package com.dongdongshop.mq;

import cn.hutool.core.util.ObjectUtil;
import com.dongdongshop.pojo.TbOrder;
import com.dongdongshop.service.TbOrderItemService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.Message;

import java.util.Objects;

@RocketMQTransactionListener
public class OrderMQListenner implements RocketMQLocalTransactionListener {

    @DubboReference
    private TbOrderItemService tbOrderItemService;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override//执行本地方法
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        String s = message.getHeaders().getId().toString();
        try {
            TbOrder tbOrder = (TbOrder) o;
            tbOrderItemService.updatezhuangtai(tbOrder.getOrderNum(), tbOrder.getOrderNo());
            redisTemplate.boundValueOps(s).set("1");
            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            e.printStackTrace();
            redisTemplate.boundValueOps(s).set("0");
            return RocketMQLocalTransactionState.ROLLBACK;
        }

    }

    @Override//回查方法
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        String s = message.getHeaders().getId().toString();
        String o = (String) redisTemplate.boundValueOps(s).get();
        if (Objects.equals(o, "1")) {
            return RocketMQLocalTransactionState.COMMIT;
        } else if (Objects.equals(o, "0")) {
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        return RocketMQLocalTransactionState.UNKNOWN;
    }
}
